<?php
/**
 * Created by PhpStorm.
 * User: Lee
 * Date: 2020/1/3
 * Time: 9:51
 */
namespace App\Services\System;

use App\Common\Exception\ErrorException;
use App\Models\System\RoleUser;
use App\Models\System\Menu;
use App\Models\System\Rolepower;
use App\Models\System\Role;

/**
 * 系统管理-角色管理 (服务)
 */
class RoleService
{
    /** @var \App\Repositories\System\RoleRepository $roleRepository */
    private $roleRepository;

    public function __construct()
    {
        $this->roleRepository = app('roleRepository');
    }

    // 获取列表
    public function getList($requestData){
        $filters = [];
        // 搜索
        if(isset($requestData['filters']['rolename']) && !empty($requestData['filters']['rolename'])){
            $filters[] = ['rolename', 'like', '%'.$requestData['filters']['rolename'].'%'];
        }

        $filters[] = ['id', '!=', SYSTEM_ROLE];

        $sorts = ['id' => 'desc'];

        $result = $this->roleRepository->getList($filters,$sorts,$requestData['page']);

        return $result->toArray();
    }

    // 获取所有角色
    public function getAll($filters=[],$sort=[],$columns = ['*']){
        return $this->roleRepository->getAll($filters,$sort,$columns);
    }

    public function get($id, $keyName = 'id',$columns = ['*']){
        return $this->roleRepository->get($id, $keyName, $columns);
    }

    // 新增
    public function add($requestData){
       // dd($requestData);
        //$id = $this->roleRepository->add($requestData);
        $id = Role::create([
            'rolename'=>$requestData['rolename'],
            // 'role_name'=>$requestData['roledes'],
            'role_type'=>$requestData['role_type'],
            'description'=>$requestData['roledes'],
            'scope_type'=>'TEACHER'
        ]);
//        $record = $record->toArray();
//        $id = $record['id'];
        return $id->id;
    }

    //编辑
    public function edit($requestData){
        $id = $requestData['id'];
        $role = $this->roleRepository->get($id);
        if(!$role){
            throw new ErrorException('角色不存在');
        }
        $id = Role::where('id',$id)->update([
            'rolename'=>$requestData['rolename'],
            // 'role_name'=>$requestData['roledes'],
            'role_type'=>$requestData['role_type'],
            'description'=>$requestData['roledes']
        ]);
        return $id;
    }

    //删除
    public function delete($requestData){
        $id = $requestData['id'];
        $role = $this->roleRepository->get($id);
        if(!$role){
            throw new ErrorException('角色不存在');
        }
        // User::where('curr_role_id', $id)->update(['curr_role_id'=>0]);
        $this->roleRepository->delete($id);
    }

    public function getPowerTree($requestData){
        $role_id = $requestData['role_id'];
        $result = Menu::where('status',1)->where('pid',0)->select('id','name as title','pid')->with([
            'children'=>function($q){
                $q->orderBy('sort');
            }
            ])->orderBy('sort')->get()->toArray();
        //获取当前用户组权限
        $roles = Rolepower::where('role_id',$role_id)->pluck('actionid')->toArray(); 

        foreach($result as $k=>&$v){
            if(!empty($v['children'])){
                foreach($v['children'] as $k2=>&$v2){                
                    if(empty($v2['children'])){
                        if(in_array($v2['id'],$roles)){
                             $v2['checked'] = true;
                        }
                    }else{
                        foreach($v2['children'] as $k3=>&$v3){
                            if(empty($v3['children'])){
                                if(in_array($v3['id'],$roles)){
                                    $v3['checked'] = true;
                                }
                            }else{
                                foreach($v3['children'] as $k4=>&$v4){
                                    if(in_array($v4['id'],$roles)){
                                        $v4['checked'] = true;
                                    }
                                }
                            }
                                                      
                        }
                    }
                }
            }
        }
   
       
        return ['menus'=>$result,'roles'=>$roles] ;
    }


    //获取角色权限
    public function getRolePowers($requestData){
        $id = $requestData['id'];
        $role = $this->roleRepository->get($id);
        if(!$role){
            throw new ErrorException('角色不存在');
        }
        $powers = $role->powers()->get();
        $powers = $powers->toArray();
        $powers = array_column($powers, 'actionid');
        return $powers;
    }

    //设置角色权限
    public function setRolePowers($requestData){
        $id = $requestData['id'];
        $role = $this->roleRepository->get($id);
        if(!$role){
            throw new ErrorException('角色不存在');
        }
        $actionids =  self::loop_menu($requestData['actionids']);  
        $insert = [];
        foreach($actionids as $k=>$v){
            $insert[$k]['role_id'] = $id;
            $insert[$k]['actionid'] = $v;
        }

        Rolepower::where('role_id',$id)->delete();
        Rolepower::insert($insert);
        return [];
    }

    //递归循环获取菜单id  lxy 2022-12-07
    private static function loop_menu($data)
    {
        static $arr = [];
        foreach($data as $k=>$v){
            array_push($arr,$v['id']);
            if(!empty($v['children'])){
                self::loop_menu($v['children']);
            }
        }
        return $arr;
    }

    /**
     * @Description: 获取角色人员
     * @Author: kzj
     * @datetime: 2022-11-26
     */
    public function getRoleUsers($request)
    {
        if(!$request['role_id']){
            throw new ErrorException('参数错误');
        }

        $result = RoleUser::where('role_id', $request['role_id'])->with('user:user_id,id,user_name')->get()->pluck('user');

        return $result;
    }

    //*******************外部调用方法****************************************************
    public function getCore($id, $keyName = 'id',$columns = ['*']){
        return $this->roleRepository->get($id,$keyName,$columns);
    }

}
